package com.javaweb.bookstore;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JdbcConnPoolExample {
    private static HikariDataSource dataSource;

    static {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        config.setUsername("username");
        config.setPassword("password");
        config.setMaximumPoolSize(20);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);

        dataSource = new HikariDataSource(config);
    }

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(10);

        // 提交多个数据库任务
        for (int i = 0; i < 20; i++) {
            final int userId = i;
            threadPool.submit(() -> {
                try {
                    getUserInfo(userId);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            });
        }

        threadPool.shutdown();
    }

    private static void getUserInfo(int userId) throws SQLException {
        String sql = "SELECT id, name, email FROM users WHERE id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                System.out.println(Thread.currentThread().getName() +
                        " - User: " + rs.getString("name") +
                        ", Email: " + rs.getString("email"));
            }
        }
    }
}